<?php

namespace App\Db;

use App\Utils\Date;
use Illuminate\Support\Facades\DB;

class Blog
{
    public const BLOG = 'blog';

    public function addNewBlog($data, $siteId)
    {
        return DB::table(self::BLOG)->insertGetId([
            'site' => $siteId,
            'title' => $data['title'],
            'category' => $data['category'],
            'content_md' => $data['content_md'],
            'content_html' => $data['content_html'],
            'url' => $data['url'] ?? '',
            'create_time' => $data['create_time'] ?? Date::now(),
            'is_del' => 0
        ]);
    }

    public function saveBlog($data, $siteId)
    {
        $d = [
            'site' => $siteId,
            'title' => $data['title'],
            'category' => $data['category'],
            'content_md' => $data['content_md'],
            'content_html' => $data['content_html'],
            'url' => $data['url'] ?? '',
            'update_time' => Date::now()
        ];
        if (isset($data['create_time']) && $data['create_time']) {
            $d['create_time'] = $data['create_time'];
        }
        return DB::table(self::BLOG)->where(['id' => $data['id']])->update($d);
    }

    public function getBlogList($params, $siteId)
    {
        $whereArr = [
            'is_del' => 0,
            'site' => $siteId
        ];
        if (isset($params['category']) && $params['category'] > 0) {
            $whereArr['category'] = $params['category'];
        }
        $limit = 20;
        if (isset($params['limit']) && $params['limit'] > 0) {
            $limit = $params['limit'];
        }
        $page = 1;
        if (isset($params['page']) && $params['page'] > 0) {
            $page = $params['page'];
        }
        list($data, $count) = [
            DB::table(self::BLOG)->where($whereArr)->select(['id', 'category', 'title', 'url', 'create_time'])->skip(($page - 1) * $limit)->limit($limit)->orderByDesc('create_time')->get()->toArray(),
            DB::table(self::BLOG)->where($whereArr)->count()
        ];

        $categorys = array_column(DB::table(Columns::TABLE)->select(['id', 'name'])->whereIn('id', array_column($data, 'category'))->get()->toArray(), null, 'id');

        array_walk($data, function($v) use($categorys) {
            $v->category_name = isset($categorys[$v->category]) ? $categorys[$v->category]->name : '';
        });

        return [
            'count' => $count,
            'data' => $data
        ];
    }

    public function deleteBlog($id)
    {
        return DB::table(self::BLOG)->where(['id' => $id])->update([
            'is_del' => 1,
            'update_time' => Date::now()
        ]);
    }

    public function getBlogRow($id)
    {
        return DB::table(self::BLOG)->where(['id' => $id, 'is_del' => 0])->first();
    }
}
